package bl.user;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

import blservice.user.UserBLService;
import po.Po;
import po.UserPo;
import dbservice.user.UserDBService;
import vo.UserVo;
import vo.Vo;

public class UserBLStub extends UnicastRemoteObject implements UserBLService{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private UserDBService userDB;
	
	public UserBLStub(UserDBService db)throws RemoteException{
		this.userDB=db;
	}
	
	public UserVo checkLogin(UserVo vo){		
		UserPo po=userDB.get(userV2P(vo));
		UserVo r=userP2V(po);
		return r;
	}
	
	private UserVo userP2V(UserPo po){
		UserVo r=new UserVo();
		if(po.isSuccessed()){
			r.successed();
			r.setName(po.getName());
			r.setUserType(po.getUserType());
			r.setAuthority(po.getAuthority());
		}else{
			r.failed(po.getFailMessage());
		}
		return r;
	}
	
	private UserPo userV2P(UserVo vo){
		UserPo po=new UserPo();
		po.setAuthority(vo.getAuthority());
		po.setName(vo.getName());
		po.setPassword(vo.getPassword());
		po.setUserType(vo.getUserType());
		return po;
	}
	
	public Vo addUser(UserVo vo){
		Po po=userDB.add(userV2P(vo));
		Vo r=new Vo();
		if(po.isSuccessed()){
			r.successed();
		}else{
			r.failed(po.getFailMessage());
		}
		return r;
	}
	
	public Vo deleteUser(UserVo vo){
		Po po=userDB.delete(userV2P(vo));
		Vo r=new Vo();
		if(po.isSuccessed()){
			r.successed();
		}else{
			r.failed(po.getFailMessage());
		}
		return r;
	}
	
	public Vo changePassword(UserVo vo){
		Po po=userDB.update(userV2P(vo));
		Vo r=new Vo();
		if(po.isSuccessed()){
			r.successed();
		}else{
			r.failed(po.getFailMessage());
		}
		return r;
	}
	
	public Vo changeAuthority(UserVo vo){
		Po po=userDB.update(userV2P(vo));
		Vo r=new Vo();
		if(po.isSuccessed()){
			r.successed();
		}else{
			r.failed(po.getFailMessage());
		}
		return r;
	}
	
	public List<UserVo> getAll(){
		List<UserPo> po=userDB.getAll();
		List<UserVo> vo=new ArrayList<UserVo>();
		for(int i=0;i<po.size();i++){
			vo.add(userP2V(po.get(i)));
		}
		return vo;
	}
	
}